<template>
	<view class="page" @touchstart="touchStart" @touchend="touchEnd">
		<form>
			<view class="uni-list list-pd">
				<view class="uni-list-cell cell-pd">
					<view class="uni-uploader">
						<view class="uni-uploader-head">
							<view class="uni-uploader-title"></view>
							<view class="uni-uploader-info">{{ imageList.length }}/9</view>
						</view>
						<view class="uni-uploader-body">
							<view class="uni-uploader__files">
								<block v-for="(image, index) in imageList" :key="index">
									<view class="uni-uploader__file" style="position: relative;">
										<image lazy-load class="uni-uploader__img" style="border-radius: 6%;" mode="aspectFill" :src="$cdn.photo + image" :data-src="image" @tap="previewImage"></image>
										<view class="close-view" @click="close(index)">×</view>
									</view>
								</block>
								<view class="uni-uploader__input-box"  v-if="imageList.length < 9">
									<view class="uni-uploader__input" @tap="chooseImage"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</form>
	</view>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import image from '@/common/image.js';
import tuiButton from '@/components/extend/button/button';
import tuiListView from '@/components/list-view/list-view';
import tuiListCell from '@/components/list-cell/list-cell';
import tuiIcon from '@/components/icon/icon';

var sourceType = [['camera'], ['album'], ['camera', 'album']];
var sizeType = [['compressed'], ['original'], ['compressed', 'original']];
export default {
	computed: mapState(['isLogin', 'token', 'headPic', 'userName', 'photos']),
	components: {
		tuiListView,
		tuiListCell,
		tuiIcon,
		tuiButton
	},
	data() {
		return {
			$cdn:this.$cdn,
			// title: 'choose/previewImage',
			imageList: [],

			sourceTypeIndex: 2,
			sourceType: ['拍照', '相册', '拍照或相册'],
			sizeTypeIndex: 2,
			sizeType: ['压缩', '原图', '压缩或原图'],
			countIndex: 8,
			count: [1, 2, 3, 4, 5, 6, 7, 8, 9],

			//侧滑返回start
			startX: 0, //点击屏幕起始位置
			movedX: 0, //横向移动的距离
			endX: 0, //接触屏幕后移开时的位置
			// 递归上传图片坐标
			currentUploadPhotoIndex: 0
			//end
		};
	},
	onUnload() {
		(this.imageList = []),
			(this.sourceTypeIndex = 2),
			(this.sourceType = ['拍照', '相册', '拍照或相册']),
			(this.sizeTypeIndex = 2),
			(this.sizeType = ['压缩', '原图', '压缩或原图']),
			(this.countIndex = 8);
	},
	onLoad() {
		if (this.photos != '' && this.photos != null && this.photos != undefined) {
			this.imageList = this.photos.split(',');
		}
	},

	methods: {
		...mapMutations(['setUserInfo']),
		uploadPhoto(tempFilePaths) {
			// setTimeout(() => {
			if (this.currentUploadPhotoIndex >= tempFilePaths.length) {
				return;
			}
			this.tui
				.uploadFile('/auth/api/member/uploadPhoto', tempFilePaths[this.currentUploadPhotoIndex])
				.then(res => {
					console.log('uploadPhoto上传结果' + JSON.stringify(res));
					if (res.code == 0) {
						this.currentUploadPhotoIndex++;
						console.log(JSON.stringify(res));
						this.setUserInfo({photos: res.data});
						this.imageList = res.data.split(',');
						// 递归保存图片
						this.uploadPhoto(tempFilePaths);
					} else {
						uni.showToast("上传失败，原因"+res.msg);
						console.log('error...');
						this.currentUploadPhotoIndex++;
						this.uploadPhoto(tempFilePaths);
					}
				})
				.catch(res => {
					console.log(res);
				});

			// }, 300);
		},

		clear: function() {
			this.hasLocation = false;
		},

		close(e) {
			uni.showModal({
				title: '提示',
				content: '是否删除该图片？',
				success: res => {
					if (res.confirm) {
						this.deleteSinglePhoto(e);
					}
				}
			});
		},
		chooseImage: async function() {
			if (this.imageList.length === 9) {
				uni.showToast({
					title: '最多只能上传9张照片',
					icon: 'error'
				});
				// let isContinue = await this.isFullImg();
				/* console.log('是否继续?', isContinue);
				if (!isContinue) {
					return;
				} */
			}
			// 重新赋值
			this.currentUploadPhotoIndex = 0;
			uni.chooseImage({
				sourceType: sourceType[this.sourceTypeIndex],
				sizeType: sizeType[this.sizeTypeIndex],
				count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[this.countIndex],
				success: res => {
					// #ifdef APP-PLUS
					//提交压缩,因为使用了H5+ Api,所以自定义压缩目前仅支持APP平台
					var compressd = cp_images => {
						this.imageList = this.imageList.concat(cp_images); //压缩后的图片路径
					};
					image.compress(res.tempFilePaths, compressd);
					// #endif

					// #ifndef APP-PLUS
					this.imageList = this.imageList.concat(res.tempFilePaths); //非APP平台不支持自定义压缩,暂时没有处理,可通过uni-app上传组件的sizeType属性压缩
					// #endif
					console.log('选择后=' + JSON.stringify(res.tempFilePaths));
					// for (var i = 0; i < res.tempFilePaths.length; i++) {
						// 实时上传相册
						this.uploadPhoto(res.tempFilePaths);
					// }
				}
			});
		},
		isFullImg: function() {
			return new Promise(res => {
				uni.showModal({
					content: '最多上传9张照片？',
					success: e => {
						if (e.confirm) {
							// this.imageList = [];
							res(true);
						} else {
							res(false);
						}
					},
					fail: () => {
						res(false);
					}
				});
			});
		},
		previewImage: function(e) {
			var current = this.$cdn.photo+e.target.dataset.src;
			let newImageList=[];
			for (var i = 0; i < this.imageList.length; i++) {
				newImageList[i]=this.$cdn.photo+this.imageList[i];
			}
			uni.previewImage({
				current: current,
				urls: newImageList,
				indicator: 'default'
			});
		},
		touchStart: function(e) {
			this.startX = e.mp.changedTouches[0].pageX;
		},

		touchEnd: function(e) {
			this.endX = e.mp.changedTouches[0].pageX;
			if (this.endX - this.startX > 200) {
				uni.navigateBack();
			}
		},
		// 删除图片
		deleteSinglePhoto(e) {
			this.imageList.splice(e, 1);
			//参数
			var photosSrc = '';
			if (this.imageList != undefined && this.imageList != '' && this.imageList.length > 1) {
				for (var i = 0; i < this.imageList.length; i++) {
					if(i==this.imageList.length-1){
						photosSrc = photosSrc + this.imageList[i];
					}else{
						photosSrc = photosSrc + this.imageList[i] + ',';
					}
				}
			} else if (this.imageList.length == 1) {
				photosSrc = this.imageList[0];
			}
			let postData = { photos: photosSrc };
			let that=this;
			this.tui
				.request('/auth/api/member/update', postData, 'POST', false, false)
				.then(res => {
					if (res.code == 0) {
						console.log('deleteSinglePhoto=' + JSON.stringify(res));
						// 更新state
						that.setUserInfo({photos:res.data.photos});
					}
				})
				.catch(res => {
					console.log(res);
				});
		}
	}
};
</script>

<style scoped>
.footer {
	margin-top: 80upx;
}

.cell-pd {
	padding: 20upx 30upx;
}

.uni-textarea {
	width: auto;
	padding: 20upx 25upx;
	line-height: 1.6;
	height: 150upx;
}
.uni-list::before {
	height: 0;
}
.uni-list:after {
	height: 0;
}
.list-pd {
	margin-top: 0;
}
.close-view {
	text-align: center;
	line-height: 30upx;
	height: 35upx;
	width: 35upx;
	background: #ef5350;
	color: #ffffff;
	position: absolute;
	top: 1upx;
	right: 1upx;
	font-size: 35upx;
	border-radius: 8upx;
}
.page {
	width: 750upx;
	height: 100%;
}

/* 发布按钮 */
.tui-btm {
	margin-bottom: 20rpx;
	padding: 0 25rpx;
}

/* 定位 */
.tui-list-view {
	padding-top: 20upx !important;
}

.tui-list-cell-name {
	padding-left: 20upx;
	vertical-align: middle;
	line-height: 30upx;
}
</style>
